import 'reflect-metadata';
import {
    Controller,
    Param,
    Body,
    Get,
    Post,
    Put,
    Delete,
    Authorized,
    CurrentUser,
    QueryParam, BodyParam, HttpError, UseBefore, JsonController
} from 'routing-controllers';
import {UserService} from "../service/UserService";
import {ResultResponse, User} from "../../pb/User";
import {TokenHelper} from "../utils/tokenHelper";
import {ServerConst} from "../config/ServerConst";
import {LogsMiddlewares} from "../middleware/LogsMiddlewares";
import {config} from "../config";
import {Service} from "typedi";

@Service()
@Controller()
@JsonController(`${config.apiurl}/user`)
export class UserController {
    @Post('/login')
    public async login(@BodyParam('username') username: string, @BodyParam('password') password: string):Promise<ResultResponse>  {
        console.log('password=',password);
        const user:User = new User();
        user.name = username;
        let findUser:User|undefined = await UserService.findOneByUser(user);
        if(!findUser){
            return new ResultResponse(-1, '未找到用户');
        }
        try{
            // const decPassword =  CryptHelper.decryptByKey(password);
            // const encryptPassword = MD5.cryptPwd(decPassword, findUser.salt);
            // if(encryptPassword !== findUser.password){
            //     return new ResultResponse(-1, '密码错误');
            // }
            const token = TokenHelper.createToken(findUser, ServerConst.tokenTimeOut)
            return new ResultResponse(1, '登录成功', {
                token:token,
                user:findUser
            });
        }catch(e){
            console.error(e);
            return new ResultResponse(1, '密码不正确');
        }
    }

    // @Post('register')
    // public register(@Body() user: User):Promise<ResultResponse>{
    //     user.salt = MD5.getRandomSalt();
    //     const decPassword = CryptHelper.decryptByKey(user.password);
    //     user.password = MD5.cryptPwd(decPassword, user.salt);
    //     // return UserService.create(user);
    // }

    // @Get('current-user')
    // @Authorized()
    // @Post('/users')
    // post(@Body() userData: any, @CurrentUser() user:any) {
    //     return 'Saving user...';
    // }
    @Post('/users')
    @UseBefore(LogsMiddlewares)
    @Authorized()
    @Get('current-user')
    async post(@Body() userData: User, @CurrentUser() user:User) {
        return 'Saving user...'+user.userId+":"+userData.userId;
    }

    @Get('/error')

    error(@QueryParam('code') code: number) {
        return code
    }
}